<template>
  <scroll-view
    id="scroll-view"
    class="scroll-view"
    scroll-y
    :style="{ height: scrollHeight + 'px' }"
    :scroll-top="scrollTop"
    scroll-with-animation
    @scroll="handleScroll"
  >
    <view class="content">
      <!-- 拼单 -->
      <view class="share-bill-section">
        <text>拼单享满减 分账无需算</text>
        <button class="share-bill-button">好友拼单</button>
      </view>
      <!-- 广告 -->
      <swiper
        class="ad-swiper"
        autoplay
        circular
      >
        <swiper-item
          class="ad-swiper-item"
          v-for="(item, index) in adImgs"
          :key="index"
        >
          <image
            class="ad-swiper-item-image"
            :src="item"
          />
        </swiper-item>
      </swiper>
      <!-- 商品列表 -->
      <view
        class="cate-section"
        v-for="(cate, cIdx) in menus"
        :key="cIdx"
        :id="`cat-${cIdx}`"
      >
        <view class="cate">
          <view>{{ cate.categoryNameSale }}</view>
        </view>
        <view class="products">
          <view
            class="product"
            v-for="(product, pIdx) in cate.products"
            :key="pIdx"
            @tap="toProductDetail(cate, product)"
          >
            <view class="product-logo">
              <image
                class="product-logo-image"
                :src="product.productLogo"
              />
            </view>
            <view class="product-info">
              <view class="mb-lg">
                <view class="product-name">
                  <view
                    class="product-name-text"
                    :style="{
                      maxWidth: product.cornerTag ? '250rpx' : '350rpx'
                    }"
                  >
                    {{ product.productName }}
                  </view>
                  <view
                    v-if="product.cornerTag"
                    class="product-corner-tag"
                    :style="[getTagStyle(product.cornerTag)]"
                  >
                    {{ product.cornerTag.content }}
                  </view>
                </view>
                <view class="product-tags">
                  <view
                    class="product-tag"
                    :style="[getTagStyle(tag)]"
                    v-for="(tag, tIdx) in product.productTags"
                    :key="tIdx"
                  >
                    {{ tag.content }}
                  </view>
                </view>
                <view class="product-desc">
                  {{ getProductShortDesc(product.productDesc) }}
                </view>
              </view>
              <view class="product-bottom">
                <view class="product-price">
                  <text class="text-xs">¥</text>
                  <text class="mx-xs">
                    {{ $tools.formatPrice(product.productPrice) }}
                  </text>
                  <text
                    class="text-xs text-color-grey"
                    v-if="product.productSpecs.length"
                    >起
                  </text>
                </view>
                <view class="product-action">
                  <image
                    v-if="hasInCart(product)"
                    src="/static/images/menu/minus.png"
                    class="product-action-icon"
                    @tap.stop="minus(product)"
                  />
                  <view
                    class="product-quantity"
                    v-if="hasInCart(product)"
                  >
                    {{ productQuantity(product) }}
                  </view>
                  <image
                    src="/static/images/menu/plus.png"
                    class="product-action-icon"
                    @tap.stop="plus(cate, product)"
                  />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </scroll-view>
</template>
<script>
import { mapState, mapActions } from "vuex"
export default {
  name: "RightContent",
  props: {
    scrollHeight: {
      type: Number,
      default: 0,
      required: true
    }
  },
  data() {
    return {
      adImgs: [
        "/static/images/menu/ads/1.jpg",
        "/static/images/menu/ads/2.jpg",
        "/static/images/menu/ads/3.jpg"
      ],
      categoryPositions: [],
      scrollTop: 0,
      scrollTimer: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.updateCategoryPositions()
    })
  },
  computed: {
    ...mapState("menu", ["menus", "currentMenuIndex", "cart"]),
    getProductShortDesc() {
      return desc => desc.split("\n")[0]
    },
    getTagStyle() {
      return tag => ({
        backgroundColor: tag.bgColor,
        color: tag.fontColor
      })
    },
    hasInCart() {
      return product =>
        this.cart.some(item => item.productId === product.productId)
    },
    productQuantity() {
      return product => {
        let items = this.cart.filter(item => item.productId == product.productId)
        return items.reduce((acc, cur) => acc + parseInt(cur.quantity), 0)
      }
    }
  },
  methods: {
    ...mapActions("menu", [
      "setCurrentMenuIndex",
      "addToCart",
      "minusQuantity"
    ]),

    toProductDetail(cate, product) {
      uni.navigateTo({
        url:
          "/pages/menu-subs/product-detail?categoryId=" +
          cate.productCategoryId +
          "&productId=" +
          product.productId
      })
    },

    plus(cate, product) {
      if (!product.productSpecs.length && !product.productAttrs.length) {
        this.addToCart({
          ...product,
          selectedAttrIds: [],
          selectedSpecs: [],
          productPrice: this.$tools.formatPrice(product.productPrice),
          attrAndSpecText: "",
          quantity: 1
        })
      } else {
        this.toProductDetail(cate, product)
      }
    },

    minus(product) {
      if (!product.productSpecs.length && !product.productAttrs.length) {
        const findIndex = this.cart.findIndex(
          item => item.productId == product.productId
        )
        this.minusQuantity(findIndex)
      } else {
        this.$store.commit("menu/SET_SHOW_CART", true)
      }
    },

    handleScroll(e) {
      const scrollTop = e.detail.scrollTop
      let tabs = this.categoryPositions
        .filter(item => item.top <= scrollTop)
        .reverse()

      if (tabs.length > 0) {
        this.setCurrentMenuIndex(tabs[0].index)
      }
    },

    updateCategoryPositions() {
      this.categoryPositions = []
      const scrollViewTop = uni.upx2px(434)
      this.menus.forEach((_, index) => {
        const el = uni.createSelectorQuery().in(this).select(`#cat-${index}`)
        el.fields(
          {
            rect: true
          },
          data => {
            if (data) {
              this.categoryPositions[index] = {
                index: index,
                top: data.top - scrollViewTop
              }
            }
          }
        ).exec()
      })
    },

    scrollToCategory(index) {
      this.scrollTop = this.categoryPositions[index]?.top || 0
    }
  }
}
</script>
<style lang="scss" scoped>
.scroll-view {
  width: 590rpx;
}

.content {
  width: 100%;
  background-color: #fff;
  padding: $uni-spacing-row-lg;
  padding-bottom: calc($uni-spacing-row-lg + 100rpx);
}

.share-bill-section {
  background-color: #f7f7f7;
  height: 90rpx;
  padding: $uni-spacing-row-base;
  margin-bottom: $uni-spacing-row-lg;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: $uni-font-size-sm;
  color: $uni-text-color;
  font-weight: 600;
  border-radius: $uni-border-radius-lg;
}

.share-bill-button {
  width: 160rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  background-color: $uni-color-primary;
  font-size: $uni-font-size-sm;
  border-radius: 45rpx;
}

.ad-swiper {
  height: 272rpx;
  margin-bottom: $uni-spacing-row-lg;
  &-item {
    height: 100%;
    border-radius: $uni-border-radius-xxl;
    &-image {
      width: 100%;
      height: 100%;
      border-radius: $uni-border-radius-xxl;
    }
  }
}

.cate {
  padding: $uni-spacing-row-lg 0;
  color: $uni-text-color;
  font-size: $uni-font-size-base;
  font-weight: 500;
}

.product {
  display: flex;
  align-items: stretch;
  padding: $uni-spacing-row-base 0;
  &-logo {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: $uni-spacing-row-base;
    &-image {
      width: 150rpx;
      height: 150rpx;
    }
  }

  &-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  &-name {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    font-size: $uni-font-size-base;
    font-weight: 600;
    color: $uni-text-color;
    margin-bottom: $uni-spacing-row-sm;

    &-text {
      max-width: 300rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  &-desc {
    font-size: $uni-font-size-sm;
    color: $uni-text-color-grey;
  }

  &-tags {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: $uni-spacing-row-sm;
    margin-bottom: $uni-spacing-row-sm;
  }

  &-tag {
    font-size: $uni-font-size-xs;
    font-weight: 500;
    color: $uni-text-color;
    padding: $uni-spacing-row-xs;
    border-radius: $uni-border-radius-lg;
  }

  &-corner-tag {
    font-size: $uni-font-size-sm;
    font-weight: 500;
    color: $uni-text-color;
    padding: $uni-spacing-row-xs;
    border-radius: $uni-border-radius-base;
    margin-left: $uni-spacing-row-sm;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  &-bottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  &-price {
    font-size: $uni-font-size-base;
    font-weight: 600;
    color: $uni-text-color;
  }

  &-action {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: $uni-spacing-row-base;

    &-icon {
      width: 46rpx;
      height: 46rpx;
    }
  }

  &-quantity {
    font-size: $uni-font-size-base;
    font-weight: 600;
    color: $uni-text-color;
  }
}
</style>
